<?php 
/**
 * Parses for example 1024KB to 1MB and so on.
 * 
 * $params array can have these arguments<br>
 * size - item size<br>
 * from - default is B. In what units size is. (B,KB,MB,GB)<br>
 * to - default is NULL. This means whatever fits best.<br>
 * 
 * @param Array $params
 * @param Smarty $smarty
 * @return String
 */
function smarty_function_fileSize($params, &$smarty) {

	$bytes = $params["size"];
	$from = strtoupper($params['from'] ? $params['from'] : 'B');
	$to = strtoupper($params['to'] ? $params['to'] : NULL);
		
	$fileConverts = array();
	$fileConverts["B"] = 1;
	$fileConverts["BYTES"] = 1;
	$fileConverts["KB"] = 1024;
	$fileConverts["KILOBYTES"] = 1024;
	$fileConverts["MB"] = 1024*1024;
	$fileConverts["MEGABYTES"] = 1024*1024;
	$fileConverts["GB"] = 1024*1024*1024;
	$fileConverts["GIGABYTES"] = 1024*1024*1024;
	$fileConverts["keys"] = array_keys( $fileConverts );
	
	$bytes = $bytes * $fileConverts[$from];
		
	if( !in_array($from, $fileConverts["keys"]) ) {
		return '0B';
	}
		
	if( $to == '' ) {
		if( $bytes > $fileConverts["GB"])
			return round($bytes / $fileConverts["GB"],1).'GB';
		
		else if( $bytes > $fileConverts["MB"] )
			return round($bytes / $fileConverts["MB"],1).'MB';
		
		else if( $bytes > $fileConverts["KB"] )
			return round($bytes / $fileConverts["KB"],1).'KB';
		
		else
			return $bytes.'B';
	
	} elseif( in_array($to, $fileConverts["keys"]) ) {
		return array(round($bytes / $fileConverts[$to],1), $to);
	}
		
	return '0B';
}


?>